(function ($) {
    $.fn.serializeFormJSON = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    var page = {
        init: function () {
            var that = this;

            that.reloadTable();

            $('#defaultForm').bootstrapValidator({
                message: "提交数据不能全部为空！",
                feedbackIcons: {
                    valid: 'mdi mdi-check',
                    invalid: 'mdi mdi-close',
                    validating: 'mdi mdi-refresh'
                },
                fields: {
                    realName: {
                        message: '真实姓名校验失败！',
                        validators: {
                            notEmpty: {
                                message: '真实姓名不能为空！'
                            }
                        }
                    }
                }
            });

            $('form').submit(function (e) {
                var flag = $(this).data("bootstrapValidator").isValid();
                if (!flag) {
                    layer.msg("填写不正确，请修改正确后提交");
                    return false;
                }

                // 控制button为提交等待效果
                var $btn = $(".btn-save").button('loading');

                e.preventDefault();
                // var data = $('#defaultForm').serialize(); // 类似get的url拼参数方式，需要转换json
                var data = $(this).serializeFormJSON();
                console.log(data);

                $.ajax({
                    type: "put",
                    url: "/users",
                    cache: false,
                    data: JSON.stringify(data),
                    dataType: "json",
                    contentType: 'application/json;charset=utf-8',
                    success: function (data) {
                        if (data.code == "0") {
                            // 正确的其他处理...
                            layer.msg(data.msg, {icon: 6});
                            $btn.button("reset");
                        } else {
                            // 错误的其他处理...
                            layer.msg(data.msg, {icon: 6});
                            $btn.button("reset");
                        }
                    },
                    error: function (E) {
                        console.log(E);
                        layer.msg('提交系统失败，请稍后再试', {icon: 6});
                    }
                });
            });

        },
        reloadTable: function () {
        }
    };

    page.init();
})(jQuery);

